// changeHcInfo.js
import {
  fetchDetailById,
  updateMedifoodInfo,
  deleteMedifoodInfo
} from '../../Service/CategoryService';
import {
  getMedifoodClassifications
} from '../../Service/ClassificationService';

Page({
  data: {
    selectedOperatorIndex: null,
    operatorOptions: [],
    showPicker: false,
    otherTitles: [{
        titleName: '适应症',
        sureName: 'indication'
      },
      {
        titleName: '配方',
        sureName: 'Medifood_recipe'
      },
      {
        titleName: '用法',
        sureName: 'Medifood_usage'
      },
      {
        titleName: '治疗疾病',
        sureName: 'treated_disease'
      },
      {
        titleName: '药膳香味',
        sureName: 'Medifood_aroma'
      },
      {
        titleName: '药膳颜色',
        sureName: 'Medifood_color'
      },
      {
        titleName: '药膳味道',
        sureName: 'Medifood_flavor'
      },
      {
        titleName: '关联症状',
        sureName: 'Associated_symptoms'
      },
      {
        titleName: '食用方法',
        sureName: 'Edible_method'
      },
      {
        titleName: '治疗部位',
        sureName: 'treatment_site'
      }
    ],
    imageSrc: [],
    caseDetail: {}, // 药膳详情数据
  },

  onLoad(options) {
    this.loadOperatorOptions(); // 在页面加载时加载分类选项数据
    const id = options.id;
    // 从本地缓存中获取药膳详情
    const cachedDetail = wx.getStorageSync('caseDetail');
    if (cachedDetail) {
      this.setData({
        caseDetail: cachedDetail,
        imageSrc: [cachedDetail.thumbs], // 设置图片数组
        selectedOperatorIndex: this.findOperatorIndex(cachedDetail.classification_id)
      });
    }

    if (id) {
      this.loadDetail(id);
    }
  },

  onShow() {
    this.loadOperatorOptions();
  },

  async loadOperatorOptions() {
    try {
      const mediclassify = await getMedifoodClassifications();
      const operatorOptions = mediclassify.map(item => ({
        name: item.name,
        id: item.id,
      }));
      this.setData({
        operatorOptions: operatorOptions
      });
    } catch (error) {
      console.error('加载药膳分类信息失败:', error);
      wx.showToast({
        title: '加载药膳分类信息失败',
        icon: 'none',
        duration: 2000
      });
    }
  },

  async loadDetail(id) {
    try {
      const detail = await fetchDetailById(id);
      //检查 detail 是否存在，并且 detail 对象中是否包含有效的 classification_id
      if (detail && detail.classification_id) {
        const index = this.findOperatorIndex(detail.classification_id);
        this.setData({
          selectedOperatorIndex: index !== -1 ? index : null,
          caseDetail: detail,
          imageSrc: [detail.thumbs], // 设置图片数组
        });
      } else {
        console.error('药膳详情中缺少分类信息或分类信息无效:', detail);
      }
    } catch (error) {
      console.error('加载详情时出错:', error);
    }
  },

  findOperatorIndex(classification_id) {
    return this.data.operatorOptions.findIndex(item => item.id === classification_id);
  },

  togglePicker() {
    this.setData({
      showPicker: !this.data.showPicker
    });
  },

  selectOption(e) {
    const selectedIndex = e.currentTarget.dataset.index;
    const selectedClassificationId = this.data.operatorOptions[selectedIndex].id;
    this.setData({
      selectedOperatorIndex: selectedIndex,
      showPicker: false,
      'caseDetail.classification_id': selectedClassificationId, // 更新药膳信息中的分类id
    });
  },

  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempFilePaths;
        this.setData({
          imageSrc: tempFilePaths
        });
      },
      fail: (err) => {
        console.error("图片上传失败", err);
      }
    });
  },

  viewImage() {
    wx.previewImage({
      urls: this.data.imageSrc
    });
  },

  onMedicineNameInput(e) {
    this.setData({
      'caseDetail.name': e.detail.value
    });
  },

  onOtherInfoInput(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;

    this.setData({
      [`caseDetail.${field}`]: e.detail.value
    });
    // 将更新的数据存储到本地缓存
    wx.setStorageSync('caseDetail', this.data.caseDetail);
  },

  async confirm() {
    wx.showLoading({
      title: '正在保存...',
      mask: true // 遮罩层
    });
    try {
      const res = await updateMedifoodInfo(this.data.caseDetail.id, this.data.caseDetail); // 更新药膳信息
      if (res) {
        wx.hideLoading();
        wx.showToast({
          title: '保存成功！',
          icon: 'success',
          duration: 2000,
        });
        // 清除本地缓存
        wx.removeStorageSync('caseDetail');
        // 延迟1秒后执行 navigateBack
        setTimeout(() => {
          wx.navigateBack();
        }, 1000);
      } else {
        wx.showToast({
          title: '保存失败！',
          icon: 'none',
          duration: 2000
        });
      }
    } catch (error) {
      wx.showToast({
        title: '保存失败！',
        icon: 'none',
        duration: 2000
      });
      console.error('保存药膳信息失败:', error);
    }
  },
  //删除药膳
  async onDeleteMedifood(infoId) {
    wx.showLoading({
      title: '正在删除...',
      mask: true // 遮罩层
    });
    try {
      const result = await deleteMedifoodInfo(infoId);
      if (result) {
        wx.hideLoading();
        wx.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 2000
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1000);
      }
    } catch (error) {
      wx.showToast({
        title: '删除失败',
        icon: 'none',
        duration: 2000
      });
      console.error('删除药膳信息失败:', error);
    }
  },

  // 调用删除方法
  delete(event) {
    const infoId = this.data.caseDetail.id; // 确保正确获取要删除的药膳信息的ID
    this.onDeleteMedifood(infoId);
  },
});